package cn.winstone;

import cn.winstone.config.Config;
import cn.winstone.enums.StatusCodeEnum;
import cn.winstone.handler.RequestHandler;
import cn.winstone.handler.ResponseHandler;
import cn.winstone.utils.ConsolePrint;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Winstone
 * @date 2020/7/29 - 10:02 上午
 */
public class HTTPServer {
    public void run() {
        try {
            // 侦听80端口
            ServerSocket server = new ServerSocket(Config.PORT);
            ConsolePrint.serverStart();

            while (true) {
                // 接收客户端请求数据
                Socket socket = server.accept();

                InputStream input = socket.getInputStream();

                RequestHandler requestHandler = new RequestHandler(input);
                String uri = requestHandler.getURI();

                String method = requestHandler.getMethod().toLowerCase();
                ConsolePrint.request(method.toUpperCase());
                BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                ResponseHandler responseHandler = new ResponseHandler();
                if (method.equals("get") || method.equals("post")) {

                    if (method.equals("get")){
                        output.write(responseHandler.getResponse(uri,StatusCodeEnum.OK));
                        output.write(responseHandler.getResource(uri));

                    }else {
                        output.write(responseHandler.getResponse(uri,StatusCodeEnum.OK));
                        output.write("这是个POST请求");
                    }

                } else {
                    ConsolePrint.serverErr(StatusCodeEnum.MethodNotAllowed);
                    output.write(responseHandler.getResponse(uri,StatusCodeEnum.MethodNotAllowed));
                    output.write(StatusCodeEnum.MethodNotAllowed.toString());
                }
                output.flush();
                input.close();
                output.close();
                socket.close();
            }
        } catch (IOException e) {
            ConsolePrint.serverErr();
        }
    }
}
